//
//  AppDelegate.swift
//  StoreManage
//
//  Created by MC on 2017/12/18.
//  Copyright © 2017年 MC. All rights reserved.
//

import UIKit

import AVFoundation


@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var speechSynthesizer : AVSpeechSynthesizer!
    var backgroundTaskIdentifier : UIBackgroundTaskIdentifier? = 0
    

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

                
        initWindow()
        setting_wx()
        setting_Jpush(application: application, launchOptions: launchOptions)
        
        return true
    }
    
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        JPUSHService.registerDeviceToken(deviceToken)
    }
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        
        let extras = userInfo["extras"] as? String ?? ""
        
//        let extras = "{\"content\":\"您有一笔新的买单完成，实付金额0.01元，请及时查看！\",\"jumpStyle\":2,\"jumpTo\":{\"type\":2,\"userId\":0},\"type\":1}"
        
        let extrasDict = MCString_createDictionaryFromJSONString(jsonString: extras)
        
        let content = extrasDict["content"] as? String ?? ""
        let type = extrasDict["type"] as? NSNumber ?? 0                    //0文字消息，1语音播报
        let jumpStyle = extrasDict["jumpStyle"] as? NSNumber ?? 1          //1不跳转，2跳转到买单列表
        let jumpTo = extrasDict["jumpTo"] as? [String : Any] ?? [:]
        let jumpType = jumpTo["type"] as? NSNumber ?? 0
        
        
        ///
        if type.intValue == 1 {
            let av = AVSpeechSynthesizer.init()
            let voice = AVSpeechSynthesisVoice.init(language: "zh-CN")
            let utterance = AVSpeechUtterance.init(string: content)
            utterance.rate = 0.5
            utterance.volume = 0.5
            utterance.voice = voice
            av.speak(utterance)
        }
        
        // 页面跳转
        if jumpStyle.intValue == 2 && MCUserinfo_getUserId() > 0 {
            MCNotification_post(name: MCNotification_Jpush, object: ["jumpType" : jumpType])
        }
        
        JPUSHService.handleRemoteNotification(userInfo)
        completionHandler(.newData)
    }
    
    
    func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
        WXApi.handleOpen(url, delegate: self)
        return true
    }
    
    func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
        WXApi.handleOpen(url, delegate: self)
        return true
    }
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
        JPUSHService.handleRemoteNotification(userInfo)
    }
    
    func applicationWillEnterForeground(_ application: UIApplication) {
        UIApplication.shared.applicationIconBadgeNumber = 0
        application.cancelAllLocalNotifications()
    }
    
    func applicationDidEnterBackground(_ application: UIApplication) {
        application.cancelAllLocalNotifications()
        application.applicationIconBadgeNumber = 0
    }
    
    
    func applicationWillResignActive(_ application: UIApplication) {
        UIApplication.shared.beginReceivingRemoteControlEvents()
        let session = AVAudioSession.sharedInstance()
        do { try session.setCategory(AVAudioSessionCategoryPlayback) } catch { }
        do { try session.setActive(true) } catch { }
        backgroundTaskIdentifier = backgroundPlayerID(backTaskId: backgroundTaskIdentifier!)
    }
    

    //MARK: -Custom Method
    func initWindow() {
        self.window = UIWindow.init(frame: UIScreen.main.bounds)
        self.window?.backgroundColor = UIColor.white
        
        if MCUserinfo_getUserId() > 0 && MCUserinfo_getStoreId() > 0 { // 登录
            let tabbarC = MCTabBarController()
            self.window?.rootViewController = tabbarC
        } else {
            let vc = MCLoginPageViewController()
            let nav = MCNavigationController.init(rootViewController: vc)
            self.window?.rootViewController = nav
        }
        self.window?.makeKeyAndVisible()
    }
    
    func setting_wx() {
        WXApi.registerApp(MCKey_wx, enableMTA: true)
    }
    
    func setting_remotePush() {
        let session = AVAudioSession.sharedInstance()
        do { try session.setCategory(AVAudioSessionCategoryPlayback) } catch { }
        do { try session.setActive(true) } catch { }
        UIApplication.shared.beginReceivingRemoteControlEvents()
    }
    
    func backgroundPlayerID(backTaskId:UIBackgroundTaskIdentifier) -> UIBackgroundTaskIdentifier {
        let session = AVAudioSession.sharedInstance()
        do { try session.setCategory(AVAudioSessionCategoryPlayback) } catch { }
        do { try session.setActive(true) } catch { }
        UIApplication.shared.beginReceivingRemoteControlEvents()
        var newTaskId : UIBackgroundTaskIdentifier!
        newTaskId = UIApplication.shared.beginBackgroundTask(expirationHandler: nil)
        
        if newTaskId != UIBackgroundTaskInvalid && backTaskId != UIBackgroundTaskInvalid {
            UIApplication.shared.endBackgroundTask(backTaskId)
        }
        return newTaskId
    }
    
    func setting_Jpush(application:UIApplication,launchOptions:[UIApplicationLaunchOptionsKey: Any]?) {
        
        if #available(iOS 10.0, *){
            let entiity = JPUSHRegisterEntity()
            entiity.types = Int(UNAuthorizationOptions.alert.rawValue |
                UNAuthorizationOptions.badge.rawValue |
                UNAuthorizationOptions.sound.rawValue)
            JPUSHService.register(forRemoteNotificationConfig: entiity, delegate: self)
        } else if #available(iOS 8.0, *) {
            let types = UIUserNotificationType.badge.rawValue |
                UIUserNotificationType.sound.rawValue |
                UIUserNotificationType.alert.rawValue
            JPUSHService.register(forRemoteNotificationTypes: types, categories: nil)
        }else {
            let type = UIRemoteNotificationType.badge.rawValue |
                UIRemoteNotificationType.sound.rawValue |
                UIRemoteNotificationType.alert.rawValue
            JPUSHService.register(forRemoteNotificationTypes: type, categories: nil)
        }
        
        JPUSHService.setup(withOption: launchOptions,
                           appKey: MCKey_Jpush,
                           channel: "app store",
                           apsForProduction: MCIP_isProduct)
        
        
        let storeId = MCUserinfo_getStoreId()
        let userId  = MCUserinfo_getUserId()
        
        JPUSHService.setAlias(String(userId), completion: nil, seq: 0)
        JPUSHService.setTags([String(storeId)], completion: nil, seq: 0)
    }
    
}


extension AppDelegate : JPUSHRegisterDelegate{
    @available(iOS 10.0, *)
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, willPresent notification: UNNotification!, withCompletionHandler completionHandler: ((Int) -> Void)!) {
       
        UIApplication.shared.applicationIconBadgeNumber = 0
        JPUSHService.setBadge(0)

        let userInfo = notification.request.content.userInfo
        if (notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self))!{
            JPUSHService.handleRemoteNotification(userInfo)
        }
        
        completionHandler(Int(UNAuthorizationOptions.alert.rawValue | UNAuthorizationOptions.sound.rawValue | UNAuthorizationOptions.badge.rawValue))// 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
    }
    
    @available(iOS 10.0, *)
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, didReceive response: UNNotificationResponse!, withCompletionHandler completionHandler: (() -> Void)!) {
       
        UIApplication.shared.applicationIconBadgeNumber = 0
        JPUSHService.setBadge(0)
        let userInfo = response.notification.request.content.userInfo
        if (response.notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self))!{
            JPUSHService.handleRemoteNotification(userInfo)
        }
        
        completionHandler()
    }
}

extension AppDelegate : WXApiDelegate {
    
    func onResp(_ resp: BaseResp!) {
        
        // 微信授权
        if resp.isKind(of: SendAuthResp.classForCoder()) {
            let aresp = resp as! SendAuthResp
            if (aresp.errCode == 0) {
                MCNotification_post(name: NOTIFICATION_WXLOGIN, object: aresp.code)
            }
        }
        
        // 微信支付
        if resp.isKind(of: PayResp.classForCoder()) {
            
            var wxPayResult : String?
            
            // WXErrCode
            switch resp.errCode {
            case 0:
                wxPayResult = "success"
                break
            case -2:
                wxPayResult = "cancel"
                break
            default:
                wxPayResult = "faile"
                break
            }
            
            MCNotification_post(name: NOTIFICATION_WXPAY, object: wxPayResult)
        }
    }
}



